import CheckTag from '@/pages/pc/components/CheckTag';
import Pagination from '@/pages/pc/components/Pagination';
import { TeacherItem } from '@/pages/pc/components/Teacher';
import { CourseItem } from '@/pages/pc/components/Course';
import { Link, useHistory, Helmet } from 'umi';
import qs from 'qs';
import styles from './index.less';
import { useState, useEffect } from 'react';
import { allGet } from '@/services/pc';
import Empty from '../components/Empty';
import { Skeleton } from 'antd';

const pageSize = 18;
const Courses = (props) => {
  const [data, setData] = useState(props.data);

  const handleRefresh = async () => {
    const totalPage = Math.floor((data?.data?.count || 5) / 5);
    const randomPage = Math.floor(Math.random() * totalPage) + 1;
    const courseParams: any = {
      mod: 'course',
      do: 'list',
      oride: 'classid',
      perpage: 5,
      page: randomPage,
      version: 'pc1.0',
    };
    const response = await allGet({ params: courseParams });
    setData(response);
  };
  return (
    <section className={styles.section}>
      <div className={styles.header}>
        <h3 className={styles.title}>推荐课程</h3>
        <div className={styles.shuaxin} onClick={handleRefresh}>
          <img
            loading="lazy"
            className={styles.icon}
            src={require('@/assets/pc/images/shuaxin.png')}
            alt=""
          />
          换一换
        </div>
      </div>
      <div className={styles.body}>
        {data?.data?.list?.map?.((item, index) => (
          <div key={item.classid} className={styles.item}>
            <CourseItem open index={index} {...item} />
          </div>
        ))}
      </div>
    </section>
  );
};

const Index = (props) => {
  const { query = {}, search, match } = props;
  const history = useHistory();
  const itemRender = (current, type, originalElement) => {
    if (type === 'page') {
      return <Link to={`/teachers/introduce/${current}${search}`}>{current}</Link>;
    }
    if (type === 'next') {
      return <Link to={`/teachers/introduce/${current}${search}`}>{originalElement}</Link>;
    }
    if (type === 'prev') {
      return <Link to={`/teachers/introduce/${current}${search}`}>{originalElement}</Link>;
    }

    return originalElement;
  };

  const handleChangeSearch = (key, value) => {
    const newQuery = query;
    newQuery[key] = value?.[0];
    const string = qs.stringify(query);
    history.push(`/teachers/introduce/${1}?${string}`);
  };
  // 分类
  const [column, setColumn] = useState<any>([]);
  useEffect(() => {
    (async () => {
      const response = await allGet({
        params: { mod: 'teacher', do: 'category', version: 'pc1.0' },
      });
      const arr: any[] =
        response?.data?.map((item) => ({ label: item.name, value: item.cid })) || [];
      arr.unshift({ label: '全部', value: '' });
      setColumn(arr);
    })();
  }, []);
  return (
    <div className={styles.page}>
      <Helmet>
        <title>讲师介绍 - CGJOY课堂</title>
        <meta name="title" content="讲师介绍 - CGJOY课堂" />
        <meta name="keywords" content={props.keywords} />
        <meta name="description" content={props.description} />
      </Helmet>
      <div className={styles.header}>
        <div className={styles.row}>
          <div className={styles.key}>分类：</div>
          <CheckTag
            data={column}
            defaultValue={[query.cid || '']}
            onChange={(value) => handleChangeSearch('cid', value)}
          />
        </div>
      </div>
      <div className={styles.main}>
        <div className={styles.list}>
          {props?.teachers?.data?.list?.length > 0 ? (
            props?.teachers?.data?.list?.map((item, index) => (
              <Link to={`/teachers/detail/${item.uid}`} key={item.uid} className={styles.item}>
                {' '}
                <TeacherItem data={item} />
              </Link>
            ))
          ) : props.initialPropsOk ? (
            <Empty style={{ margin: '100px auto 100px auto' }} />
          ) : (
            <div
              style={{
                display: 'grid',
                width: '100%',
                gridTemplateColumns: '1fr 1fr 1fr 1fr',
                gap: 20,
              }}
            >
              {new Array(20).fill(1).map((num, index) => (
                <Skeleton key={index + num} active />
              ))}
            </div>
          )}
        </div>
      </div>
      {props?.teachers?.data?.count > pageSize && (
        <Pagination
          pageSize={pageSize}
          itemRender={itemRender}
          className={styles.pagination}
          total={props?.teachers?.data?.count}
          current={parseInt(match?.params?.page)}
        />
      )}

      {/* {props?.courses?.data?.list.length > 0 && <Courses data={props?.courses} />} */}
    </div>
  );
};

Index.getInitialProps = async ({ match, history, isServer }) => {
  const { query, search } = history?.location || {};

  const params: any = {
    mod: 'teacher',
    do: 'list',
    perpage: pageSize,
    page: match?.params?.page,
    version: 'pc1.0',
  };
  const courseParams: any = {
    mod: 'course',
    do: 'list',
    oride: 'classid',
    perpage: 5,
    page: 1,
    version: 'pc1.0',
  };

  if (query.cid) {
    params.cid = query.cid;
  }

  const [teachers, columnResponse] = await Promise.all([
    allGet({ params }),
    // allGet({ params: courseParams }),
    allGet({
      params: { mod: 'teacher', do: 'category', version: 'pc1.0' },
    }),
  ]);
  const keywords = (columnResponse.data?.map?.((item) => item.name + '讲师') || []).join(',');
  const description = (teachers?.data?.list?.map?.((item) => item.username + '老师') || [])
    .join(',')
    .slice(0, 100);
  return {
    initialPropsOk: true,
    teachers,
    // courses,
    match,
    query,
    search,
    isServer,
    keywords,
    description,
  };
};

export default Index;
